<template> <!-- 闲置商品详情页面 -->
	<view class="container">
		<!-- 用户信息 -->
		<view class="user-info" @click="GoToComments">
			<view class="user-avatar">
				<image :src="avatar || '/static/pic/user.png'" mode="aspectFill"></image>
			</view>
			<view class="user-details">
				<text class="username">{{nickname}}</text>
				<view class="credit-rating">
					<text class="rating-text">信用等级:</text>
					<text class="rating-level">
						<!-- 信用等级 1极差 2一般 3良好 4优秀 5极好 -->
						<text v-if="sellerLevel === 1">(极差)</text>
						<text v-else-if="sellerLevel === 2">(一般)</text>
						<text v-else-if="sellerLevel === 3">(良好)</text>
						<text v-else-if="sellerLevel === 4">(优秀)</text>
						<text v-else-if="sellerLevel === 5">(极好)</text>
						<text v-else>(未知)</text>
					</text>
				</view>
			</view>
		</view>

		<!-- 商品信息 -->
		<view class="goods-info">
			<view class="price-section">
				<text class="price">¥{{price}}</text>
				<text class="original-price">¥{{originalPrice}}</text>
				<text class="discount">
					{{ (price / originalPrice * 10).toFixed(1) }}折
				</text>
			</view>
			<text class="goods-title">{{goodsName}}</text>
			<text class="goods-desc">{{introduce}}
			</text>

		</view>

		<!-- 商品图片 -->
		<view class="goods-image">
			<u-swiper height="700" :list="list" duration="500" :circular="true" indicator-pos="bottomRight"
				interval="3000"></u-swiper>
		</view>

		<!-- 联系方式 -->
		<view class="goods-concat">
			<text>微信号：{{wechatId}}</text>
			<br />
			<text>手机号：{{phoneNum}}</text>



		</view>
		<!-- 商品更新时间 -->
		<view class="update-time">

			<text>更新时间: {{updatedAt}}</text>
		</view>



		<!-- 底部导航栏 -->
		<view class="navigation">
			<view class="left">
				<view class="item report" @click="GoToReport">
					<u-icon name="server-fill" :size="40" :color="$u.color['contentColor']"></u-icon>
					<view class="text u-line-1">举报</view>
				</view>
				<view class="item index" @click="GoToIndex">
					<u-icon name="home" :size="40" :color="$u.color['contentColor']"></u-icon>
					<view class="text u-line-1">首页</view>
				</view>
				<view class="item car" @click="GoToCart">
					<!-- <u-badge class="car-num" :count="9" type="error" :offset="[-3, -6]"></u-badge> -->
					<u-icon name="shopping-cart" :size="40" :color="$u.color['contentColor']"></u-icon>
					<view class="text u-line-1">收藏</view>
				</view>
			</view>
			<view class="right">
				<view class="cart btn u-line-1" @click="addCart">加入收藏</view>
				<view class="buy btn u-line-1" @click="BuyNow">立即购买</view>
			</view>
		</view>
	</view>

</template>

<script setup>
	import {
		getUserInfoApi
	} from '/src/api/user.js'
	import {
		createOrderApi
	} from '/src/api/order.js'
	import {
		isAddApi,
		toggleApi
	} from '/src/api/cart.js'
	import {
		onLoad
	} from "@dcloudio/uni-app"
	import {
		reactive,
		ref
	} from 'vue'
	const avatar =ref('')
	
	// 获取卖家信息
	const fetchSellerInfo = async (userId) => {
		try {
			const res = await getUserInfoApi(userId)
			if (res && res.code === 200) {
				console.log(res)
				nickname.value = res.data.nickname
				sellerLevel.value = res.data.level
				avatar.value = res.data.avatar
			}

		} catch (error) {
			console.error('获取卖家信息失败:', error)
			uni.showToast({
				title: '获取卖家信息失败',
				icon: 'none'
			})
		}
	}

	const GoToComments = () => {
		console.log("GoToComments")
		uni.navigateTo({
			url: `/pages/SellerComments/SellerComments?sellerId=${orderModel.sellerId}`
		})
	}



	const GoToIndex = () => {
		console.log("GoToIndex")
		uni.switchTab({
			url: '/pages/index/index',

		})
	}
	const GoToReport = () => {
		console.log("GoToReport")

		console.log(goodsId.value)
		console.log(orderModel.goodsId)
		uni.navigateTo({
			url: `/pages/report/report?goodsId=${orderModel.goodsId}`
		})
	}
	const GoToCart = () => {
		console.log("GoToCart")
		uni.switchTab({
			url: '/pages/cart/cart',

		})
	}

	const orderModel = reactive({
		orderId: 0,
		goodsId: 0,
		buyerId: uni.getStorageSync("userId"),
		sellerId: 0,
		price: 0,

	})
	// 添加到收藏
	const addCart = async () => {
		console.log("addCart")
		let userId = uni.getStorageSync("userId");

		// 先检查商品状态
		if (status.value == 0) {
			uni.showToast({
				title: '该商品已经下架',
				icon: 'none',
				mask: true,
				duration: 2000,
			});
			return;
		}

		// 先检查是否已收藏
		let checkRes = await isAddApi({
			goodsId: goodsId.value,
			userId
		});
		if (checkRes && checkRes.code == 200 && checkRes.data === 1) {
			uni.showToast({
				title: '商品已在收藏夹',
				icon: 'none',
				mask: true,
				duration: 2000,
			});
			return;
		}

		// 执行收藏操作
		let res = await toggleApi({
			goodsId: goodsId.value,
			userId
		});
		if (res && res.code == 200) {
			console.log(res);
			uni.showToast({
				title: '添加收藏成功',
				icon: 'success',
				mask: true,
				duration: 2000,
			});
		}
	};

	const BuyNow = async () => {
		console.log("BuyNow")
		// console.log(sellerId.value , orderModel.buyerId)
		console.log(orderModel.sellerId, orderModel.buyerId)
		// 先检查商品状态
		if (status.value == 0) {
			uni.showToast({
				title: '该商品已经下架咯',
				icon: 'none',
				mask: true,
				duration: 2000
			});
			return;
		}

		// 再检查是否自买自卖,mask设置透明蒙层防止穿透
		if (orderModel.sellerId == orderModel.buyerId) {
			uni.showToast({
				title: '不能购买自己发布的商品',
				icon: 'none',
				mask: true,
				duration: 2000
			});
			return;
		}
		// 创建订单
		// console.log(orderModel)
		let res = await createOrderApi(orderModel)
		if (res && res.code == 200) {
			status.value = 0;
			uni.showToast({
				title: '交易成功',
				icon: 'success',
				mask: true,
				duration: 2000
			})
			// 延迟2秒后跳转（与Toast持续时间一致）
			setTimeout(() => {
				uni.switchTab({
					url: '/pages/index/index'
				});
			}, 2000);
		}


	}
	const nickname = ref('')
	const sellerLevel = ref(0)

	const goodsId = ref(0)
	const goodsName = ref('')
	const price = ref(0)
	const originalPrice = ref(0)
	const introduce = ref('')
	const phoneNum = ref('')
	const wechatId = ref('')
	const updatedAt = ref('')
	const list = ref([])
	const status = ref(0)
	onLoad((options) => {
		// 传递过来是json
		// console.log(options)
		const goods = JSON.parse(options.goods)
		// 转换成字符串
		console.log(goods)
		fetchSellerInfo(goods.userId)
		goodsId.value = goods.goodsId
		orderModel.goodsId = goods.goodsId

		goodsName.value = goods.goodsName
		// nickname.value = goods.nickname

		// sellerId.value = goods.userId
		orderModel.sellerId = goods.userId

		price.value = goods.price
		orderModel.price = goods.price

		originalPrice.value = goods.originalPrice
		introduce.value = goods.introduce
		phoneNum.value = goods.phoneNum
		wechatId.value = goods.wechatId

		updatedAt.value = goods.updatedAt.substring(0, 16).replace("T"," "); // 截取前16个字符（YYYY-MM-DD HH:mm）
		status.value = goods.status
		if (goods.image) {
			list.value = goods.image.split(',')
		}
	})
</script>

<style lang="scss">
	.container {
		padding: 20rpx;
		background-color: #f7f7f7;
		min-height: 100vh;
	}

	.user-info {
		display: flex;
		align-items: center;
		padding: 20rpx;
		background-color: #fff;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

		.user-avatar {
			width: 80rpx;
			height: 80rpx;
			border-radius: 50%;
			overflow: hidden;
			margin-right: 20rpx;

			image {
				width: 100%;
				height: 100%;
			}
		}

		.user-details {
			flex: 1;

			.username {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
				display: block;
				margin-bottom: 8rpx;
			}

			.credit-rating {
				display: flex;
				align-items: center;

				.rating-text {
					font-size: 24rpx;
					color: #666;
					margin-right: 10rpx;
				}



				.rating-level {
					font-size: 24rpx;
					color: #666;
					margin-left: 10rpx;
				}
			}
		}
	}

	.goods-info {
		padding: 20rpx;
		background-color: #fff;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

		.price-section {
			display: flex;
			align-items: center;
			margin-bottom: 20rpx;

			.price {
				font-size: 40rpx;
				font-weight: bold;
				color: #ff2e4d;
				margin-right: 15rpx;
			}

			.original-price {
				font-size: 28rpx;
				color: #999;
				text-decoration: line-through;
				margin-right: 15rpx;
			}

			.discount {
				font-size: 24rpx;
				color: #fff;
				background-color: #ff2e4d;
				padding: 4rpx 12rpx;
				border-radius: 6rpx;
			}
		}

		.goods-title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
			display: block;
			margin-bottom: 20rpx;
			line-height: 1.4;
		}

		.goods-desc {
			font-size: 28rpx;
			color: #666;
			line-height: 1.6;
		}
	}

	.goods-image {
		border-radius: 12rpx;
		overflow: hidden;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.update-time {
		font-size: 24rpx;
		color: #999;
		text-align: right;
		padding: 10rpx 20rpx;
		background-color: #fff;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.goods-concat {
		font-size: 30rpx;
		color: #999;
		text-align: left;
		padding: 10rpx 20rpx;
		background-color: #fff;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.comment-section {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		margin-bottom: 100rpx;

		.section-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
			padding-bottom: 15rpx;
			border-bottom: 1rpx solid #eee;
			margin-bottom: 20rpx;
		}

		.comment-item {
			display: flex;
			margin-bottom: 30rpx;
			padding-bottom: 20rpx;
			border-bottom: 1rpx dashed #eee;

			&:last-child {
				margin-bottom: 0;
				padding-bottom: 0;
				border-bottom: none;
			}

			.comment-user {
				width: 80rpx;
				margin-right: 20rpx;

				image {
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;
					margin-bottom: 10rpx;
				}

				text {
					font-size: 24rpx;
					color: #666;
					display: block;
					text-align: center;
				}
			}

			.comment-content {
				flex: 1;

				.comment-rating {
					margin-bottom: 10rpx;

					.star {
						font-size: 24rpx;
						color: #ccc;

						&.filled {
							color: #ffb400;
						}
					}
				}

				.comment-text {
					font-size: 28rpx;
					color: #333;
					line-height: 1.6;
					display: block;
					margin-bottom: 10rpx;
				}

				.comment-time {
					font-size: 24rpx;
					color: #999;
				}
			}
		}
	}

	.navigation {
		position: fixed; // 固定定位
		bottom: 0; // 固定在底部
		display: flex;
		margin-top: 100rpx;
		border: solid 2rpx #f2f2f2;
		background-color: #ffffff;
		padding: 16rpx 0;

		.left {
			display: flex;
			font-size: 20rpx;

			.item {
				margin: 0 30rpx;

				&.car {
					text-align: center;
					position: relative;

					.car-num {
						position: absolute;
						top: -10rpx;
						right: -10rpx;
					}
				}
			}
		}

		.right {
			display: flex;
			font-size: 28rpx;
			align-items: center;

			.btn {
				line-height: 66rpx;
				padding: 0 30rpx;
				border-radius: 36rpx;
				color: #ffffff;
			}

			.cart {
				background-color: #ff7900;
				margin-right: 30rpx;
			}

			.buy {
				background-color: #E30131;
			}
		}
	}
</style>